package com.jsyl.lwbk.business.service.education.impl;

import com.jsyl.lwbk.business.domain.Child;
import com.jsyl.lwbk.business.domain.education.*;
import com.jsyl.lwbk.business.dto.*;
import com.jsyl.lwbk.business.dto.education.CourseListDTO;
import com.jsyl.lwbk.business.dto.education.TrainingProgramChildRecordListDTO;
import com.jsyl.lwbk.business.dto.education.TrainingReportDTO;
import com.jsyl.lwbk.business.mapper.education.ChildCourseMapper;
import com.jsyl.lwbk.business.mapper.education.ChildMonthPlanMapper;
import com.jsyl.lwbk.business.mapper.education.ChildTrainingProgramMapper;
import com.jsyl.lwbk.business.mapper.education.TrainingProgramChildRecordMapper;
import com.jsyl.lwbk.business.service.IChildService;
import com.jsyl.lwbk.business.service.education.IChildCourseService;
import com.jsyl.lwbk.business.service.education.IChildTrainingProgramService;
import com.jsyl.lwbk.business.service.education.ITrainingProgramChildRecordService;
import com.jsyl.lwbk.common.exception.BusinessException;
import com.jsyl.lwbk.common.utils.DateUtils;
import com.jsyl.lwbk.common.utils.StringUtils;
import com.jsyl.lwbk.system.utils.DictUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author jh
 * @date 2020-11-02 16:18
 * @desc
 **/
@Service
public class TrainingProgramChildRecordServiceImpl implements ITrainingProgramChildRecordService {


    @Autowired
    private TrainingProgramChildRecordMapper trainingProgramChildRecordMapper;

    @Autowired
    private ChildTrainingProgramMapper childTrainingProgramMapper;

    @Autowired
    private IChildTrainingProgramService iChildTrainingProgramService;


    @Autowired
    private IChildCourseService childCourseService;


    @Autowired
    private IChildService childService;

    @Autowired
    private ChildCourseMapper childCourseMapper;

    @Autowired
    private ChildMonthPlanMapper childMonthPlanMapper;

    @Override
    public List<TrainingProgramChildRecord> list(TrainingProgramChildRecordListDTO trainingProgramChildRecordListDTO) {
        TrainingProgramChildRecordExample example = new TrainingProgramChildRecordExample();
        TrainingProgramChildRecordExample.Criteria criteria = example.createCriteria();
        criteria.andChildIdEqualTo(trainingProgramChildRecordListDTO.getChildId());
        if (trainingProgramChildRecordListDTO.getCenterId() != null) {
            criteria.andCenterIdEqualTo(trainingProgramChildRecordListDTO.getCenterId());
        }
        if (trainingProgramChildRecordListDTO.getCourseId() != null) {
            criteria.andCourseIdEqualTo(trainingProgramChildRecordListDTO.getCourseId());
        }
        if (!StringUtils.isEmpty(trainingProgramChildRecordListDTO.getTrainingProgramNumber())) {
            criteria.andTrainingProgramNumberEqualTo(trainingProgramChildRecordListDTO.getTrainingProgramNumber());
        }
        if (trainingProgramChildRecordListDTO.getQuestionId() != null) {
            criteria.andQuestionIdEqualTo(trainingProgramChildRecordListDTO.getQuestionId());
        }
        if (trainingProgramChildRecordListDTO.getTrainingScore() != null) {
            criteria.andTrainingScoreEqualTo(trainingProgramChildRecordListDTO.getTrainingScore());
        }
        if (trainingProgramChildRecordListDTO.getTrainingLevel() != null) {
            criteria.andTrainingLevelEqualTo(trainingProgramChildRecordListDTO.getTrainingLevel());
        }
        if (trainingProgramChildRecordListDTO.getProjectType() != null) {
            criteria.andProjectTypeEqualTo(trainingProgramChildRecordListDTO.getProjectType());
        }
        if (!StringUtils.isEmpty(trainingProgramChildRecordListDTO.getTrainingTime())) {
            criteria.andTrainingTimeEqualTo(trainingProgramChildRecordListDTO.getTrainingTime());
        }
//        example.setOrderByClause("training_level asc,update_time desc");

        List<TrainingProgramChildRecord> trainingProgramChildRecords = trainingProgramChildRecordMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(trainingProgramChildRecords)) {
            for (TrainingProgramChildRecord trainingProgramChildRecord : trainingProgramChildRecords) {
                if (trainingProgramChildRecord.getTrainingType() != null && trainingProgramChildRecord.getTrainingType() == 2) {
                    trainingProgramChildRecord.setTrainingContent("*" + trainingProgramChildRecord.getTrainingContent());
                }

                if (trainingProgramChildRecord.getNoTraining() != null && trainingProgramChildRecord.getNoTraining() == 1) {
                    trainingProgramChildRecord.setTrainingLevel(5);
                }
            }
        }
        return trainingProgramChildRecords;
    }

    @Override
    public String getLastTrainingTime(TrainingProgramChildRecordListDTO trainingProgramChildRecordListDTO) {
        TrainingProgramChildRecordExample example = new TrainingProgramChildRecordExample();
        TrainingProgramChildRecordExample.Criteria criteria = example.createCriteria();
        if (trainingProgramChildRecordListDTO.getChildId() != null) {
            criteria.andChildIdEqualTo(trainingProgramChildRecordListDTO.getChildId());
        }
        if (trainingProgramChildRecordListDTO.getCenterId() != null) {
            criteria.andCenterIdEqualTo(trainingProgramChildRecordListDTO.getCenterId());
        }
        if (trainingProgramChildRecordListDTO.getCourseId() != null) {
            criteria.andCourseIdEqualTo(trainingProgramChildRecordListDTO.getCourseId());
        }
        if (!StringUtils.isEmpty(trainingProgramChildRecordListDTO.getTrainingProgramNumber())) {
            criteria.andTrainingProgramNumberEqualTo(trainingProgramChildRecordListDTO.getTrainingProgramNumber());
        }
        if (trainingProgramChildRecordListDTO.getQuestionId() != null) {
            criteria.andQuestionIdEqualTo(trainingProgramChildRecordListDTO.getQuestionId());
        }
        if (trainingProgramChildRecordListDTO.getTrainingScore() != null) {
            criteria.andTrainingScoreEqualTo(trainingProgramChildRecordListDTO.getTrainingScore());
        }
        if (trainingProgramChildRecordListDTO.getTrainingLevel() != null) {
            criteria.andTrainingLevelEqualTo(trainingProgramChildRecordListDTO.getTrainingLevel());
        }
        if (trainingProgramChildRecordListDTO.getProjectType() != null) {
            criteria.andProjectTypeEqualTo(trainingProgramChildRecordListDTO.getProjectType());
        }
        if (trainingProgramChildRecordListDTO.getCheckTime() != null) {
            if (trainingProgramChildRecordListDTO.getCheckTime() == 1) {
                if (!StringUtils.isEmpty(trainingProgramChildRecordListDTO.getTrainingTime())) {
                    criteria.andTrainingTimeLessThan(trainingProgramChildRecordListDTO.getTrainingTime());
                }
            } else {
                if (!StringUtils.isEmpty(trainingProgramChildRecordListDTO.getTrainingTime())) {
                    criteria.andTrainingTimeEqualTo(trainingProgramChildRecordListDTO.getTrainingTime());
                }
            }
        }
        example.setOrderByClause("training_time desc,create_time desc");
        List<TrainingProgramChildRecord> trainingProgramChildRecords = trainingProgramChildRecordMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(trainingProgramChildRecords)) {
            return trainingProgramChildRecords.get(0).getTrainingTime();
        }
        return null;
    }

    @Override
    @Transactional
    public void saveEntering(List<TrainingProgramChildRecord> records,Long loginUserId, String loginName) {
        DecimalFormat df = new DecimalFormat("0.00");
        Long childId = null, courseId = null;
        Integer projectType = null;
        String centerId = null, teacherName = null, trainingTime = null;
        for (TrainingProgramChildRecord trainingProgramChildRecord : records) {
            childId = trainingProgramChildRecord.getChildId();
            courseId = Long.valueOf(DateUtils.parseDateToStr("yyyyMMdd",DateUtils.getNowDate())+String.valueOf(childId));
            trainingProgramChildRecord.setCourseId(courseId);
            centerId = trainingProgramChildRecord.getCenterId().toString();
            projectType = trainingProgramChildRecord.getProjectType();
            teacherName = loginName;
            trainingTime = trainingProgramChildRecord.getTrainingTime();
            if (trainingProgramChildRecord.getId() != null) {
                //查询该项目当天是否已经录入过
                TrainingProgramChildRecordExample example = new TrainingProgramChildRecordExample();
                example.createCriteria().andChildTrainingProgramIdEqualTo(trainingProgramChildRecord.getId()).andTrainingTimeEqualTo(trainingProgramChildRecord.getTrainingTime()).andCourseIdEqualTo(courseId);
                List<TrainingProgramChildRecord> trainingProgramChildRecords = trainingProgramChildRecordMapper.selectByExample(example);
                //有录入过则更新
                if (!CollectionUtils.isEmpty(trainingProgramChildRecords)) {
                    ChildTrainingProgram childTrainingProgram = iChildTrainingProgramService.findById(trainingProgramChildRecord.getId());
                    if (childTrainingProgram != null) {
                        String correctNum = childTrainingProgram.getModifyContent().split("\\[")[1].split("\\]")[0];
                        String modifyNum = childTrainingProgram.getModifyTrainingContent()==null?correctNum:childTrainingProgram.getModifyTrainingContent().split("\\[")[1].split("\\]")[0];
                        TrainingProgramChildRecord old = trainingProgramChildRecords.get(0);
                        old.setTotalNum(trainingProgramChildRecord.getTotalNum());
                        old.setCompleteNum(trainingProgramChildRecord.getCompleteNum());
                        old.setNoTraining(trainingProgramChildRecord.getNoTraining());
                        if(trainingProgramChildRecord.getNoTraining().equals(1)){
                            old.setCompleteNum(null);
                            old.setTotalNum(null);
                        }
                        if (trainingProgramChildRecord.getNoTraining().equals(0)
                                &&trainingProgramChildRecord.getCompleteNum() != null
                                && trainingProgramChildRecord.getTotalNum() != null
                                && trainingProgramChildRecord.getTotalNum() != 0
                                && childTrainingProgram.getInputType().equals(3)) {
                            //次数
//                            String rate1 = df.format((double) trainingProgramChildRecord.getCompleteNum() / trainingProgramChildRecord.getTotalNum());
                            String rate = getRate(childTrainingProgram.getInputType(),childTrainingProgram.getModifyDirection(), Integer.valueOf(correctNum), Integer.valueOf(modifyNum), trainingProgramChildRecord.getCompleteNum(), trainingProgramChildRecord.getTotalNum());
                            old.setCompleteRate(rate);
                            old.setTrainingLevel(getTraningLevel(Double.parseDouble(rate), old));
                        } else if(trainingProgramChildRecord.getNoTraining().equals(0)
                                &&trainingProgramChildRecord.getCompleteNum() != null
                                && !childTrainingProgram.getInputType().equals(3)){
                            //时间、距离计算是否达成
                            String rate = getRate(childTrainingProgram.getInputType(),childTrainingProgram.getModifyDirection(), Integer.valueOf(correctNum), Integer.valueOf(modifyNum), trainingProgramChildRecord.getCompleteNum(), 0);
                            old.setCompleteRate(rate);
                            old.setTrainingLevel(getTraningLevel(Double.parseDouble(rate), old));

                        }else {
                            //已稳定，没有录入成绩的情况
                            if (trainingProgramChildRecord.getTrainingLevel() != null && trainingProgramChildRecord.getTrainingLevel() == 0) {
                                old.setCompleteRate("1");
                                old.setTrainingLevel(0);
                            } else {
                                old.setCompleteRate("0");
                                old.setTrainingLevel(3);
                            }
                        }
                        old.setUpdateBy(loginName);
                        old.setUpdateTime(new Date());
                        trainingProgramChildRecordMapper.updateByExample(old, example);
                    }
                }
                //没录入过则插入
                else {
                    TrainingProgramChildRecord tpcr = getTpcr(trainingProgramChildRecord, loginName);
                    if (tpcr != null) {
                        trainingProgramChildRecordMapper.insert(tpcr);
                    }
                }


            }
        }
        //保存最后更新人
        if (!CollectionUtils.isEmpty(records)) {
            courseId = records.get(0).getCourseId();
            if (courseId != null) {
                ChildCourseExample childCourseExample = new ChildCourseExample();
                childCourseExample.createCriteria().andIdEqualTo(courseId);
                List<ChildCourse> childCourses = childCourseMapper.selectByExample(childCourseExample);
                if (!CollectionUtils.isEmpty(childCourses)) {
                    ChildCourse childCourse = childCourses.get(0);
                    childCourse.setUpdateBy(loginName);
                    childCourseMapper.updateByExample(childCourse, childCourseExample);
                }
            }
        }
        //插入报告表
        ChildReport childReport = new ChildReport();
        childReport.setChildId(childId);
        childReport.setCourseId(courseId);
        ChildReport local = this.childMonthPlanMapper.getChildMonthPlan(childReport);
        if (null == local) {
            childReport.setTrainingProgramNumber(trainingTime);
            childReport.setProjectType(projectType);
            childReport.setCenterId(centerId);
            childReport.setReportType(3);
            childReport.setStatus(0);
            childReport.setCreateBy(teacherName);
            childReport.setCreateTime(DateUtils.getNowDate());
            childReport.setUpdateBy(teacherName);
            childReport.setUpdateTime(DateUtils.getNowDate());
            this.childMonthPlanMapper.insert(childReport);
        } else {
            local.setCenterId(centerId);
            local.setUpdateBy(teacherName);
            local.setUpdateTime(DateUtils.getNowDate());
            this.childMonthPlanMapper.updateById(local);
        }
    }

    /**
     * @param inputType  输入类型：1-时间，2-距离，3-次数
     * @param modifyDirection:修改方向，1-增加，2-减少
     * @param correctNum                     原标准次数
     * @param modifyNum                      修改后标准
     * @param totalNum                       尝试回合
     * @param completeNum                    完成回合
     * @return
     */
    private String getRate(Integer inputType,Integer modifyDirection, Integer correctNum, Integer modifyNum, Integer completeNum, Integer totalNum) {
        String result = "0";
        DecimalFormat df = new DecimalFormat("0.00");
        if (inputType.equals(3) && modifyDirection.equals(1) && modifyNum < correctNum) {
            return result;
        }
        if (inputType.equals(3) && modifyDirection.equals(1) && modifyNum >= correctNum) {
            result = df.format((double) completeNum / totalNum);
            return result;
        }

        if (inputType.equals(3) && modifyDirection.equals(2) && modifyNum > correctNum) {
            return result;
        }
        if (inputType.equals(3) && modifyDirection.equals(2) && modifyNum <= correctNum) {
            result = df.format((double) completeNum / totalNum);
            return result;
        }

        //时间距离类 增加修改时
        if(!inputType.equals(3) && modifyDirection.equals(1) && completeNum >= correctNum){
            return "1";
        }
        if(!inputType.equals(3) && modifyDirection.equals(1) && completeNum < correctNum){
            return "0";
        }

        //时间距离类 减小修改时
        if(!inputType.equals(3) && modifyDirection.equals(2) && completeNum <= correctNum){
            return "1";
        }
        if(!inputType.equals(3) && modifyDirection.equals(2) && completeNum > correctNum){
            return "0";
        }
        return result;
    }

    private TrainingProgramChildRecord getTpcr(TrainingProgramChildRecord trainingProgramChildRecord, String loginName) {
        DecimalFormat df = new DecimalFormat("0.00");
        ChildTrainingProgram childTrainingProgram = iChildTrainingProgramService.findById(trainingProgramChildRecord.getId());
//        if (childTrainingProgram != null) {
//            TrainingProgramChildRecord tpcr = new TrainingProgramChildRecord();
//            String correctNum = childTrainingProgram.getModifyContent().split("\\[")[1].split("\\]")[0];
//            String modifyNum = childTrainingProgram.getModifyTrainingContent()==null?correctNum:childTrainingProgram.getModifyTrainingContent().split("\\[")[1].split("\\]")[0];
//            BeanUtils.copyProperties(childTrainingProgram, tpcr);
//            tpcr.setId(null);
//            tpcr.setCourseId(trainingProgramChildRecord.getCourseId());
//            tpcr.setChildTrainingProgramId(trainingProgramChildRecord.getId());
//            tpcr.setTrainingTime(trainingProgramChildRecord.getTrainingTime());
//            tpcr.setTotalNum(trainingProgramChildRecord.getTotalNum());
//            tpcr.setCompleteNum(trainingProgramChildRecord.getCompleteNum());
//            tpcr.setNoTraining(trainingProgramChildRecord.getNoTraining());
//            if(trainingProgramChildRecord.getNoTraining().equals(1)){
//                tpcr.setCompleteNum(null);
//                tpcr.setTotalNum(null);
//            }
//            tpcr.setTeacherId(trainingProgramChildRecord.getTeacherId());
//            tpcr.setTeacherName(trainingProgramChildRecord.getTeacherName());
//            if (trainingProgramChildRecord.getCompleteNum() != null && trainingProgramChildRecord.getTotalNum() != null && trainingProgramChildRecord.getTotalNum() != 0) {
////                String rate1 = df.format((double) trainingProgramChildRecord.getCompleteNum() / trainingProgramChildRecord.getTotalNum());
//                String rate = getRate(childTrainingProgram.getInputType(),childTrainingProgram.getModifyDirection(), Integer.valueOf(correctNum), Integer.valueOf(modifyNum), trainingProgramChildRecord.getCompleteNum(), trainingProgramChildRecord.getTotalNum());
//                tpcr.setCompleteRate(rate);
//                tpcr.setTrainingLevel(getTraningLevel(Double.parseDouble(rate), tpcr));
//            } else {
//                if (trainingProgramChildRecord.getTrainingLevel() != null && trainingProgramChildRecord.getTrainingLevel() == 1) {
//                    tpcr.setCompleteRate("1");
//                    tpcr.setTrainingLevel(0);
//                } else {
//                    tpcr.setCompleteRate("0");
//                    tpcr.setTrainingLevel(3);
//                }
//            }
//            tpcr.setCreateBy(loginName);
//            tpcr.setUpdateBy(loginName);
//            tpcr.setCreateTime(new Date());
//            tpcr.setUpdateTime(new Date());
//            Child child = childService.findById(childTrainingProgram.getChildId());
//            if (child != null) {
//                tpcr.setChildName(child.getName());
//            }

        TrainingProgramChildRecord tpcr = new TrainingProgramChildRecord();
        BeanUtils.copyProperties(childTrainingProgram, tpcr);
            tpcr.setId(null);
            tpcr.setCourseId(trainingProgramChildRecord.getCourseId());
            tpcr.setChildTrainingProgramId(trainingProgramChildRecord.getId());
            tpcr.setTrainingTime(trainingProgramChildRecord.getTrainingTime());
        String correctNum = childTrainingProgram.getModifyContent().split("\\[")[1].split("\\]")[0];
        String modifyNum = childTrainingProgram.getModifyTrainingContent()==null?correctNum:childTrainingProgram.getModifyTrainingContent().split("\\[")[1].split("\\]")[0];
        tpcr.setTotalNum(trainingProgramChildRecord.getTotalNum());
        tpcr.setCompleteNum(trainingProgramChildRecord.getCompleteNum());
        tpcr.setNoTraining(trainingProgramChildRecord.getNoTraining());
        if(trainingProgramChildRecord.getNoTraining().equals(1)){
            tpcr.setCompleteNum(null);
            tpcr.setTotalNum(null);
        }
        if (trainingProgramChildRecord.getNoTraining().equals(0)
                &&trainingProgramChildRecord.getCompleteNum() != null
                && trainingProgramChildRecord.getTotalNum() != null
                && trainingProgramChildRecord.getTotalNum() != 0
                && childTrainingProgram.getInputType().equals(3)) {
            //次数
//                            String rate1 = df.format((double) trainingProgramChildRecord.getCompleteNum() / trainingProgramChildRecord.getTotalNum());
            String rate = getRate(childTrainingProgram.getInputType(),childTrainingProgram.getModifyDirection(), Integer.valueOf(correctNum), Integer.valueOf(modifyNum), trainingProgramChildRecord.getCompleteNum(), trainingProgramChildRecord.getTotalNum());
            tpcr.setCompleteRate(rate);
            tpcr.setTrainingLevel(getTraningLevel(Double.parseDouble(rate), tpcr));
        } else if(trainingProgramChildRecord.getNoTraining().equals(0)
                &&trainingProgramChildRecord.getCompleteNum() != null
                && !childTrainingProgram.getInputType().equals(3)){
            //时间、距离计算是否达成
            String rate = getRate(childTrainingProgram.getInputType(),childTrainingProgram.getModifyDirection(), Integer.valueOf(correctNum), Integer.valueOf(modifyNum), trainingProgramChildRecord.getCompleteNum(), 0);
            tpcr.setCompleteRate(rate);
            tpcr.setTrainingLevel(getTraningLevel(Double.parseDouble(rate), tpcr));

        }else {
            //已稳定，没有录入成绩的情况
            if (trainingProgramChildRecord.getTrainingLevel() != null && trainingProgramChildRecord.getTrainingLevel() == 0) {
                tpcr.setCompleteRate("1");
                tpcr.setTrainingLevel(0);
            } else {
                tpcr.setCompleteRate("0");
                tpcr.setTrainingLevel(3);
            }


        }
        return tpcr;
    }

    /**
     * 判断项目是否已稳定：1-已达成，2-需巩固，3-未达成，0-已稳定
     *
     * @param rate
     * @param tcpr
     * @return
     */
    private Integer getTraningLevel(double rate, TrainingProgramChildRecord tcpr) {
        Integer tl = null;
        if (rate >= 0.7) {
            tl = 1;
        } else if (rate > 0.4 && rate <= 0.69) {
            tl = 2;
        } else if (rate <= 0.4) {
            tl = 3;
        }
        //查询是否已经连续3天已达成
        if (tl == 1) {
            //昨天
//            Integer preDayLevel = getLevel(tcpr.getChildTrainingProgramId(), DateUtils.getPreDateByDate(tcpr.getTrainingTime()));
            //前天
//            Integer prePreDayLevel = getLevel(tcpr.getChildTrainingProgramId(), DateUtils.getPreDateByDate(DateUtils.getPreDateByDate(tcpr.getTrainingTime())));
            //判断前两节课达成数
            int reachCount = this.trainingProgramChildRecordMapper.selectReachCount(tcpr.getChildId(),tcpr.getTrainingProgramId(),tcpr.getTrainingProgramNumber());
            //更新项目为已稳定
            //0为已稳定
            if (reachCount >=2) {
                tl = 0;
                ChildTrainingProgram childTrainingProgram = new ChildTrainingProgram();
                childTrainingProgram.setId(tcpr.getChildTrainingProgramId());
                childTrainingProgram.setTrainingLevel(0);
                ChildTrainingProgramExample example = new ChildTrainingProgramExample();
                example.createCriteria().andIdEqualTo(tcpr.getChildTrainingProgramId());
                childTrainingProgramMapper.updateByExampleSelective(childTrainingProgram, example);

            }

        }
        return tl;
    }

    private Integer getLevel(Long id, String dateDay) {
        Integer level = null;
        TrainingProgramChildRecordExample example = new TrainingProgramChildRecordExample();
        example.createCriteria().andChildTrainingProgramIdEqualTo(id).andTrainingTimeEqualTo(dateDay);
        List<TrainingProgramChildRecord> trainingProgramChildRecords = trainingProgramChildRecordMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(trainingProgramChildRecords)) {
            level = trainingProgramChildRecords.get(0).getTrainingLevel();
        }
        return level;
    }


    @Override
    public TrainingReportDTO findTrainingReport(TrainingProgramChildRecordListDTO trainingProgramChildRecordListDTO) {
        if (trainingProgramChildRecordListDTO.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        if (trainingProgramChildRecordListDTO.getChildId() == null) {
            throw new BusinessException("小孩ID为空");
        }
        DecimalFormat df = new DecimalFormat("0.00");
        TrainingReportDTO trainingReportDTO = new TrainingReportDTO();
        trainingReportDTO.setChildName(trainingProgramChildRecordListDTO.getChildName());
        trainingReportDTO.setScheduleTime(trainingProgramChildRecordListDTO.getTrainingProgramNumber());
        if (!StringUtils.isEmpty(trainingProgramChildRecordListDTO.getTrainingProgramNumber())) {
            trainingReportDTO.setMonthTime(trainingProgramChildRecordListDTO.getTrainingProgramNumber().split("-")[1] + "月");
        }
        TrainingProgramChildRecordExample example = new TrainingProgramChildRecordExample();
        TrainingProgramChildRecordExample.Criteria criteria = example.createCriteria();
        criteria.andCenterIdEqualTo(trainingProgramChildRecordListDTO.getCenterId()).andChildIdEqualTo(trainingProgramChildRecordListDTO.getChildId()).andTrainingProgramNumberEqualTo(trainingProgramChildRecordListDTO.getTrainingProgramNumber());
        List<TrainingProgramChildRecord> trainingProgramChildRecords = trainingProgramChildRecordMapper.selectByExample(example);
//        if(CollectionUtils.isEmpty(trainingProgramChildRecords)){
//            throw new BusinessException("暂无记录");
//        }
        String teacherName1 = "-";
        String teacherName2 = "-";
        String teacherName3 = "-";
        String rateStr1 = "-";
        String rateStr2 = "-";
        String rateStr3 = "-";
        String rateStr4 = "-";
        String rateStr5 = "-";
        String rateStr6 = "-";
        String rateStr7 = "-";
        String rateStr8 = "-";
        String program1 = "-";
        String program2 = "-";
        String program3 = "-";
        String program4 = "-";
        String program5 = "-";
        String program6 = "-";
        String program7 = "-";
        String program8 = "-";
        String program9 = "-";
        Long childId = trainingProgramChildRecordListDTO.getChildId();
        if (childId != null) {
            trainingReportDTO.setChildId(childId);
            Child child = childService.findById(childId);
            if (child != null) {
                trainingReportDTO.setChildName(child.getName());
                if (!StringUtils.isEmpty(child.getBirthYear())) {
                    Integer birthYear = Integer.parseInt(child.getBirthYear());
                    int curYear = DateUtils.getYear(new Date());
                    trainingReportDTO.setChildAge((curYear - birthYear) + "周岁");
                }
            }
        }
        //设置责任老师姓名
        trainingReportDTO.setChildId(childId);
        CourseListDTO courseListDTO = new CourseListDTO();
        courseListDTO.setCenterId(trainingProgramChildRecordListDTO.getCenterId());
        courseListDTO.setChildId(childId);
        courseListDTO.setScheduleTime(trainingProgramChildRecordListDTO.getTrainingProgramNumber());
        courseListDTO.setScheduleType(1);
        teacherName1 = childCourseService.getTeacherName(courseListDTO);
        trainingReportDTO.setTeacherName1(teacherName1);
        courseListDTO.setScheduleType(3);
        teacherName2 = childCourseService.getTeacherName(courseListDTO);
        trainingReportDTO.setTeacherName2(teacherName2);
        courseListDTO.setScheduleType(2);
        teacherName3 = childCourseService.getTeacherName(courseListDTO);
        trainingReportDTO.setTeacherName3(teacherName3);


        List<TrainingProgramChildRecord> trainingProgramChildRecords78 = new ArrayList<TrainingProgramChildRecord>();
        List<ChildTrainingProgram> childTrainingPrograms78 = new ArrayList<ChildTrainingProgram>();
        for (int i = 1; i <= 9; i++) {
            //查询当月训练项目总数
            ChildTrainingProgramExample childTrainingProgramExample = new ChildTrainingProgramExample();
            ChildTrainingProgramExample.Criteria childTrainingProgramExampleCriteria = childTrainingProgramExample.createCriteria();
            childTrainingProgramExampleCriteria.andCenterIdEqualTo(trainingProgramChildRecordListDTO.getCenterId()).andTrainingProgramNumberEqualTo(trainingProgramChildRecordListDTO.getTrainingProgramNumber());
            childTrainingProgramExampleCriteria.andChildIdEqualTo(childId);
            childTrainingProgramExampleCriteria.andTrainingModuleEqualTo(i);
            childTrainingProgramExampleCriteria.andIsChoosedEqualTo(1);
            List<ChildTrainingProgram> childTrainingProgramList = childTrainingProgramMapper.selectByExample(childTrainingProgramExample);
            if (!CollectionUtils.isEmpty(childTrainingProgramList)) {
                String program = getProgram(childTrainingProgramList);
                if (i == 1) {
                    program1 = program;
                } else if (i == 2) {
                    program2 = program;
                } else if (i == 3) {
                    program3 = program;
                } else if (i == 4) {
                    program4 = program;
                } else if (i == 5) {
                    program5 = program;
                } else if (i == 6) {
                    program6 = program;
                } else if (i == 7) {
                    program7 = program;
                } else if (i == 8) {
                    program8 = program;
                } else if (i == 9) {
                    program9 = program;
                }

            }
            if (!CollectionUtils.isEmpty(trainingProgramChildRecords)) {
                //查询已达成记录
                TrainingProgramChildRecordExample trainingProgramChildRecordExample = new TrainingProgramChildRecordExample();
                TrainingProgramChildRecordExample.Criteria trainingProgramChildRecordExampleCriteria = trainingProgramChildRecordExample.createCriteria();
                trainingProgramChildRecordExampleCriteria.andCenterIdEqualTo(trainingProgramChildRecordListDTO.getCenterId()).andChildIdEqualTo(trainingProgramChildRecordListDTO.getChildId()).andTrainingProgramNumberEqualTo(trainingProgramChildRecordListDTO.getTrainingProgramNumber())
                        .andTrainingModuleEqualTo(i).andTrainingLevelEqualTo(1);
                List<TrainingProgramChildRecord> trainingProgramChildRecordList = trainingProgramChildRecordMapper.selectByExample(trainingProgramChildRecordExample);
                String rateStr = "-";
                if (CollectionUtils.isEmpty(trainingProgramChildRecordList)) {
                    rateStr = "0%";

                } else {
                    if (i == 7 || i == 8) {
                        //去除每天训练重复的
                        List<TrainingProgramChildRecord> records = removeDuplicateRecord(trainingProgramChildRecordList);
                        trainingProgramChildRecords78.addAll(records);
                        childTrainingPrograms78.addAll(childTrainingProgramList);
                    } else {
                        if (CollectionUtils.isEmpty(childTrainingProgramList)) {
                            rateStr = "0%";
                        } else {
                            //去除每天训练重复的
                            List<TrainingProgramChildRecord> records = removeDuplicateRecord(trainingProgramChildRecordList);
                            String data = df.format((double) records.size() / childTrainingProgramList.size());
                            if (!StringUtils.isEmpty(data)) {
                                rateStr = (Double.parseDouble(data) * 100) + "%";
                            }
                        }
                    }
                }

                if (i == 1) {
                    rateStr1 = rateStr;
                } else if (i == 2) {
                    rateStr2 = rateStr;
                } else if (i == 3) {
                    rateStr3 = rateStr;
                } else if (i == 4) {
                    rateStr4 = rateStr;
                } else if (i == 5) {
                    rateStr5 = rateStr;
                } else if (i == 6) {
                    rateStr6 = rateStr;
                } else if (i == 8) {
                    if (CollectionUtils.isEmpty(trainingProgramChildRecords78)) {
                        rateStr7 = "0%";
                    } else {
                        if (CollectionUtils.isEmpty(childTrainingPrograms78)) {
                            rateStr7 = "0%";
                        } else {
                            double trainingModule1Rate =(double) trainingProgramChildRecords78.size() / childTrainingPrograms78.size();
                            BigDecimal b = new BigDecimal(trainingModule1Rate);
                            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            rateStr7 = (f1 * 100) + "%";
                            trainingProgramChildRecords78.clear();
                            childTrainingPrograms78.clear();
                        }
                    }
                } else if (i == 9) {
                    rateStr8 = rateStr;
                }

            }

        }


        trainingReportDTO.setRateStr1(rateStr1);
        trainingReportDTO.setRateStr2(rateStr2);
        trainingReportDTO.setRateStr3(rateStr3);
        trainingReportDTO.setRateStr4(rateStr4);
        trainingReportDTO.setRateStr5(rateStr5);
        trainingReportDTO.setRateStr6(rateStr6);
        trainingReportDTO.setRateStr7(rateStr7);
        trainingReportDTO.setRateStr8(rateStr8);
        trainingReportDTO.setProgram1(program1);
        trainingReportDTO.setProgram2(program2);
        trainingReportDTO.setProgram3(program3);
        trainingReportDTO.setProgram4(program4);
        trainingReportDTO.setProgram5(program5);
        trainingReportDTO.setProgram6(program6);
        trainingReportDTO.setProgram7(program7);
        trainingReportDTO.setProgram8(program8);
        trainingReportDTO.setProgram9(program9);
        return trainingReportDTO;

    }

    private String getProgram(List<ChildTrainingProgram> childTrainingProgramList) {
        String program = "";
        for (ChildTrainingProgram childTrainingProgram : childTrainingProgramList) {
            program = program + childTrainingProgram.getTrainingName() + "<br/>";
        }
        return program;
    }

    //去除重复同一个训练项目每天训练多次达成的情况
    private List<TrainingProgramChildRecord> removeDuplicateRecord(List<TrainingProgramChildRecord> list) {
        List<TrainingProgramChildRecord> tem = new ArrayList<TrainingProgramChildRecord>();
        tem.addAll(list);
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).getChildTrainingProgramId().equals(list.get(i).getChildTrainingProgramId())) {
                    TrainingProgramChildRecord trainingProgramChildRecord = list.get(j);
                    tem.remove(trainingProgramChildRecord);
                }
            }
        }
        return tem;
    }

    @Override
    public ChildCourseScoreDTO getChildCourseScoreReport(Long id) {
        ChildCourseScoreDTO result = new ChildCourseScoreDTO();
        List<TrainingProgramChildRecord> list = this.trainingProgramChildRecordMapper.getChildCourseScore(id);
        List<ChildCourseScoreDetail> temp = new ArrayList<>();
        for (TrainingProgramChildRecord t : list) {
            if (result.getReportName() == null) {
                String projectName = DictUtils.getDictLabel("business_project_type", t.getProjectType().toString()).replaceAll("\r", "");
                result.setChildName(t.getChildName());
                result.setChildId(t.getChildId());
                result.setCourseDate(t.getDayDate().split("-")[0] + "年" + t.getDayDate().split("-")[1] + "月" + t.getDayDate().split("-")[2] + "日");
                result.setReportName(projectName + "的训练报告");
            }
            ChildCourseScoreDetail detail = new ChildCourseScoreDetail();
            detail.setCompleteRate(t.getCompleteRate());
            if(t.getInputType().equals(1) && t.getCompleteNum()!=null){
                detail.setAvgTime(t.getCompleteNum().toString());
            }
            if(t.getInputType().equals(2) && t.getCompleteNum()!=null){
                detail.setAvgDistance(t.getCompleteNum().toString());
            }
            detail.setInputType(t.getInputType().toString());
            detail.setTrainingContent(t.getTrainingContent());
            detail.setTrainingLevel(DictUtils.getDictLabel("business_training_level", t.getTrainingLevel().toString()));
            temp.add(detail);
        }
        result.setList(temp);
        return result;
    }

    @Override
    public ChildMonthResultDTO getChildCourseMonthScoreReport(Long id) {
        List<ChildMonthResultVO> list = this.trainingProgramChildRecordMapper.getChildMonthResult(id);
        List<ChildMonthResultVO> listCount = this.trainingProgramChildRecordMapper.getChildClassCount(id);
        ChildMonthResultDTO resultDTO = new ChildMonthResultDTO();
        List<ChildMonthPlanDetailDTO> languageList = new ArrayList<>();
        List<ChildMonthPlanDetailDTO> knowledgeList = new ArrayList<>();
        List<ChildMonthPlanDetailDTO> sportList = new ArrayList<>();
        Map<Integer, Integer> moduleMap = new HashMap<>();
        for (ChildMonthResultVO vo : list) {
            resultDTO.setChildId(vo.getChildId());
            resultDTO.setChildName(vo.getChildName());
            resultDTO.setPlanName(vo.getTrainingProgramNumber().split("-")[0] + "年" + vo.getTrainingProgramNumber().split("-")[1] + "月训练小结");
            moduleMap.put(vo.getTrainingModule(), vo.getProjectType());
        }

        for (ChildMonthResultVO vo : listCount) {
            if (vo.getProjectType().equals(1)) {
                resultDTO.setSportTips(vo.getChildName() + "本月完成了" + vo.getClassCount() + "节感知觉与运动训练");
            }
            if (vo.getProjectType().equals(2)) {
                resultDTO.setKnowledgeTips(vo.getChildName() + "本月完成了" + vo.getClassCount() + "节认知训练");
            }
            if (vo.getProjectType().equals(3)) {
                resultDTO.setLanguageTips(vo.getChildName() + "本月完成了" + vo.getClassCount() + "节言语与语言训练");
            }
        }

        for (Map.Entry<Integer, Integer> m : moduleMap.entrySet()) {
            ChildMonthPlanDetailDTO tempDto = new ChildMonthPlanDetailDTO();
            Integer stableRate=0, reachRate=0,consolidateRate=0,noReachRate=0;
            for (ChildMonthResultVO vo : list) {
                if (m.getKey().equals(vo.getTrainingModule())) {
                    if (tempDto.getModuleName() == null) {
                        tempDto.setModuleName(DictUtils.getDictLabel("business_training_module", vo.getTrainingModule().toString()).replaceAll("\r", "") + "训练");
                        List<String> tempList = new ArrayList<>();
                        tempDto.setTrainingNames(tempList);
                    }
                    List<String> tempList = tempDto.getTrainingNames();
                    String temp =dealTrainingLevel(vo.getTrainingLevel());
                    if(temp.equals("(已稳定)")){
                        stableRate++;
                    }
                    if(temp.equals("(已达成)")){
                        reachRate++;
                    }
                    if(temp.equals("(需巩固)")){
                        consolidateRate++;
                    }
                    if(temp.equals("(未达成)")){
                        noReachRate++;
                    }
                    tempList.add(vo.getTrainingContent() + temp);
                    tempDto.setTrainingNames(tempList);
                }
            }
            DecimalFormat df = new DecimalFormat("0.00");
            tempDto.setStableRate(df.format((double) stableRate / tempDto.getTrainingNames().size()));
            tempDto.setReachRate(df.format((double) reachRate / tempDto.getTrainingNames().size()));
            tempDto.setConsolidateRate(df.format((double) consolidateRate / tempDto.getTrainingNames().size()));
            tempDto.setNoReachRate(df.format((double) noReachRate / tempDto.getTrainingNames().size()));

            if (m.getValue() == 1) {
                sportList.add(tempDto);
            }
            if (m.getValue() == 2) {
                knowledgeList.add(tempDto);
            }
            if (m.getValue() == 3) {
                languageList.add(tempDto);
            }
        }
        resultDTO.setKnowledgeList(knowledgeList);
        resultDTO.setLanguageList(languageList);
        resultDTO.setSportList(sportList);
        return resultDTO;
    }

    /**
     * 月成绩判断
     * 按照本月每个项目填写成绩的次数与成绩结果，换算每个项目当月成绩，除【已稳定】成绩外，取当月该项目出现最多的成绩。
     * 如项目A本月填写成绩10次，5次达成（非连续），3次需巩固，2次未达标，该项目记作【已达成】。
     * 相同数量的成绩，取成绩的低值，如项目A本月填写成绩9次，3次达成（非连续），3次需巩固，3次未达标，该项目记作【未达成】。
     *
     * @return
     */
    private String dealTrainingLevel(String scores) {
        List<String> list = Arrays.asList(scores.split(","));
        if (scores.contains("0")) {
            return "(已稳定)";
        }
        Map<String, Long> map = list.stream().
                collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        if (map.containsKey("3")) {
            if (map.containsKey("2") && map.get("3") >= map.get("2")) {
                if (map.containsKey("1") && map.get("3") >= map.get("1")) {
                    return "(未达成)";
                }
            }
            if (map.containsKey("1") && map.get("3") >= map.get("1")) {
                return "(未达成)";
            }
        }
        if (map.containsKey("2")) {
            if (map.containsKey("1") && map.get("2") >= map.get("1")) {
                return "(需巩固)";
            }
        }
        if (map.containsKey("1")) {
            return "(已达成)";
        }
        if (map.containsKey("2")) {
            return "(需巩固)";
        }
        if (map.containsKey("3")) {
            return "(未达成)";
        }
        return "";
    }

}
